import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Radio, Tag, Button,Select, Popconfirm, Modal, message } from 'antd';
import { useState, useEffect, useRef } from "react";
import { getCommentList, deleteCommentApi } from "@/services/comment"
import { getIssueById } from "@/services/issue"
import { getUserById } from "@/services/user"
import { getBookByIdApi } from "@/services/book"
import TagContainer from "../components/tagContainer"
import { formatTime } from "@/utils/formatTime"
import style from "./comment.module.css"
import { useDispatch, useSelector } from '@umijs/max';

export default function Comment() {
  // type的初始值设为1
  const dispatch = useDispatch();
  const {typeList} = useSelector(state=>state.type)

  const [isModalShow, setModalShow] = useState(false)
  const [commentInfo, setCommentInfo] = useState({})
  const tableRef = useRef()
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(5)
  const [type, setType] = useState(1)
  useEffect(()=>{
    if(typeList.length===0){
      // 请求数据
      dispatch({
        type:'type/_initList'
      })
    }else{
      console.log("已经有数据了,不用请求了")
    }
  },[])
  const selectOptions = typeList.map((item)=>{
    return {
      label:item.typeName,
      value:item._id
    }
  })
  function handleTypeChagne(e) {
    console.log(e.target.value)
    setType(e.target.value)
    // 重新加载表格
    tableRef.current.reload()
  }
  function handlePageChange(newPage) {
    // 设置新页数
    setCurrent(newPage)
  }
  function confirm(rows) {
    // 删除评论
    // 根据当前的type删除对应的评论
    console.log(rows._id);
    deleteCommentApi(rows._id).then(res => {
      message.success('删除成功');
      // 强制更新
      tableRef.current.reload()

    })
  }
  function handleDetail(rows) {
    setModalShow(true)
    console.log(rows)
    setCommentInfo(rows)
  }
  function handleModalCancel() {
    setModalShow(false)

  }
  const columns = [
    {
      search:false,
      align: 'center',
      title: '序号',
      key: 'number',
      render: (_, rows, index) => {
        return (current - 1) * pageSize + index + 1;

      }
    },
    {
      search:false,

      align: 'center',
      title: type === 1 ? '问题标题' : '书籍标题',
      key: type === 1 ? 'issueTitle' : 'bookTitle',
      dataIndex: type === 1 ? 'issueTitle' : 'bookTitle',

    },
    {
      align: 'center',
      title: '评论内容',
      key: "commentContent",
      dataIndex: 'commentContent',
      render: (txt) => {
        const reg = /<[\/]?\w+>/g
        let tempStr = txt.replaceAll(reg, '');
        const showText = tempStr.slice(0, 15) + '....'
        return (<span>{showText}</span>)
      }
    },
    {
      search:false,
      align: 'center',
      title: '评论用户',
      key: 'nickname',
      dataIndex: 'nickname',
      render: (txt) => {
        return <Tag color="blue">{txt}</Tag>
      }
    },
    {
      align: 'center',
      title: '评论分类',
      dataIndex: 'typeId',
      key: 'typeId',
      render: (txt) => {
        return (<TagContainer typeId={txt} />)
      },
      renderFormItem:()=>{
        return  (
          <Select
           
            options={selectOptions}
          />
        )
      }

    },
    {
      search:false,
      align: 'center',
      title: '操作',
      key: 'options',
      render: (_, rows) => {
        return (
          <>

            <Button type="link" size="small" onClick={() => { handleDetail(rows) }}>
              详情
            </Button>
            <Popconfirm
              title="删除书籍"
              description="确定删除当前书籍"
              okText="确定"
              cancelText="取消"
              onConfirm={() => {
                confirm(rows);
              }}
            >
              <Button type="link" size="small" >
                删除
              </Button>
            </Popconfirm>
          </>
        )
      }

    }
  ]
  return (
    <PageContainer>
      <Radio.Group defaultValue={1}
        style={{
          margin: '15px 0 ',
        }}
        onChange={handleTypeChagne}>
        <Radio.Button value={1}>问答评论</Radio.Button>
        <Radio.Button value={2}>书籍评论</Radio.Button>
      </Radio.Group>
      <ProTable
        actionRef={tableRef}
        pagination={{
          defaultPageSize: pageSize,
          onChange: handlePageChange
        }}
        request={async (params) => {
          params.current = current
          params.pageSize = pageSize
          const resp = await getCommentList(type, params)
          console.log(resp);
          const tempArr = resp.data.data;
          // 这个位置开始要区分问答评论还是书籍评论
          let resList
          if (type === 1) {
            const taskList = tempArr.map((item) => {
              return getIssueById(item.issueId).then(res => {
                return {
                  ...item,
                  issueTitle: res.data.issueTitle
                }
              })
            })
            resList = await Promise.all(taskList);
          } else {
            const taskList = tempArr.map(item => {
              return getBookByIdApi(item.bookId).then(res => {
                return {
                  ...item,
                  bookTitle: res.data.bookTitle
                }
              })
            })
            resList = await Promise.all(taskList);

          }

          // console.log(resList,"结果列表")
          // ------
          // 还要处理用户列表
          const userTask = resList.map(item => {
            return getUserById(item.userId).then(res => {
              return {
                ...item,
                nickname: res.data.nickname
              }
            })
          })
          const resListWithUser = await Promise.all(userTask);
          console.log(resListWithUser, "带用户信息")
          // 除了要请求当前列表还要请求具体文章

          return {
            data: resListWithUser,
            success: true,
            total: resp.data.count
          }
        }}
        columns={columns}
        rowKey={(row) => {
          return row._id
        }}
      ></ProTable>
      <Modal open={isModalShow}
        title="评论详情"
        onCancel={handleModalCancel}
        style={{ top: 50 }}
        footer={false}
      >
        <h3>评论类型</h3>
        <Tag color="purple">
          {type === 1 ? '问答评论' : '书籍评论'}
        </Tag>
        <h3 style={{ marginTop: '10px' }}>{type === 1 ? '问答标题' : '书籍标题'}</h3>
        <p style={{ fontWeight: 'bold' }}>{type === 1 ? commentInfo.issueTitle : commentInfo.bookTitle}</p>
        <h3 style={{ marginTop: '10px' }}>评论人</h3>
        <Tag color="yellow">
          {commentInfo.nickname}
        </Tag>
        <h3 style={{ marginTop: '10px' }}>评论时间</h3>
        <Tag color="green">
          {formatTime(commentInfo.commentDate, true)}
        </Tag>
        <h3 style={{ marginTop: '10px' }}>评论内容</h3>
        <div className={style.container} dangerouslySetInnerHTML={{ __html: commentInfo.commentContent }}></div>
      </Modal>
    </PageContainer>
  )
}
